def extract_last_number(line):
    """从逗号分隔的行中提取最后一个数字"""
    try:
        return line.strip().split(',')[-1]
    except IndexError:
        return None  # 处理空行或无逗号的情况

def extract_last_number_sink(line):
    """从空格分隔的行中提取最后一个数字"""
    try:
        return line.strip().split()[-1]
    except IndexError:
        return None  # 处理空行或无空格的情况


def compare_files(source_path, sink_path, output_path):
    """比较两个文件最后一列数字，输出匹配行到新文件"""
    # 读取source文件并构建字典：{最后数字: [对应行列表]}
    source_dict = {}
    with open(source_path, 'r') as f_source:
        for line in f_source:
            last_num = extract_last_number(line)
            
            # 如果提取到的数字不为None，则将行添加到字典中
            if last_num is not None:
                source_dict.setdefault(last_num, []).append(line.strip())

    # 读取sink文件并查找匹配项
    with open(sink_path, 'r') as f_sink, open(output_path, 'w') as f_output:
        for line in f_sink:
            last_num = extract_last_number_sink(line)
            
            if last_num in source_dict:
                #如果last_num = 109806220 跳过
                if last_num == '109806220':
                    continue 
                # 写入source文件中的匹配行
                for source_line in source_dict[last_num]:
                    f_output.write(f"SOURCE: {source_line}\n")
                    #如果该最后数字是第一次出现，将最后数字写入last_num.txt中
                    with open('./caches_data/nokia_path/last_num.txt', 'a') as f_last_num:
                        f_last_num.write(f"{last_num}\n")

                # 写入sink文件中的当前行
                f_output.write(f"SINK: {line.strip()}\n\n")


Source_path = './caches_data/nokia_path/source_path.txt'  # 源文件路径
Sink_path = './caches_data/nokia_path/sink_path.txt'      # 目标文件路径
Output_path = './caches_data/nokia_path/common.txt'  # 输出文件路径


# 调用示例
compare_files(Source_path, Sink_path, Output_path)